package com.ioftv.config;

import com.ioftv.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT认证过滤器
 * 用于拦截请求并验证JWT Token
 */
@Component
public class JwtAuthenticationFilter implements HandlerInterceptor {
    
    @Autowired
    private JwtUtil jwtUtil;
    
    // 不需要认证的路径
    private static final String[] EXCLUDE_PATHS = {
        "/admin/login",
        "/admin/logout"
    };
    
    @Override
    public boolean preHandle(HttpServletRequest request, 
                            HttpServletResponse response, 
                            Object handler) throws IOException {
        
        // 获取请求路径
        String requestURI = request.getRequestURI();
        
        // 检查是否需要跳过认证
        if (shouldSkipAuthentication(requestURI)) {
            return true;
        }
        
        // 从请求头中获取Token
        String authorizationHeader = request.getHeader("Authorization");
        
        // 检查Token是否存在
        if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"未提供有效的认证Token\",\"data\":null}");
            return false;
        }
        
        // 提取JWT Token
        String token = authorizationHeader.substring(7);
        
        // 验证Token有效性
        if (!jwtUtil.validateToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期\",\"data\":null}");
            return false;
        }
        
        // 检查Token是否过期
        if (jwtUtil.isTokenExpired(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"Token已过期\",\"data\":null}");
            return false;
        }
        
        // 将用户信息存入请求属性中
        request.setAttribute("userId", jwtUtil.getUserIdFromToken(token));
        request.setAttribute("username", jwtUtil.getUsernameFromToken(token));
        request.setAttribute("role", jwtUtil.getRoleFromToken(token));
        
        // 继续执行
        return true;
    }
    
    /**
     * 判断是否需要跳过认证
     * @param requestURI 请求URI
     * @return 是否跳过认证
     */
    private boolean shouldSkipAuthentication(String requestURI) {
        // 检查是否为排除路径
        for (String excludePath : EXCLUDE_PATHS) {
            if (requestURI.equals(excludePath)) {
                return true;
            }
        }
        return false;
    }
}